package cn.com.nxt.txb.education.fragment;

import android.Manifest;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.database.Cursor;
import android.hardware.Camera;
import android.hardware.SensorManager;
import android.opengl.GLSurfaceView;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.SystemClock;
import android.provider.ContactsContract;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.OrientationEventListener;
import android.view.Surface;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
//
//
//import com.ksyun.media.diversity.screenstreamer.kit.KSYScreenStreamer;
//import com.ksyun.media.streamer.encoder.VideoEncodeFormat;
//import com.ksyun.media.streamer.framework.AVConst;
//import com.ksyun.media.streamer.kit.StreamerConstants;
//import com.ksyun.media.streamer.logstats.StatsLogReport;
import com.google.gson.Gson;
import com.ksyun.media.diversity.screenstreamer.kit.AudioInputBase;
import com.ksyun.media.diversity.screenstreamer.kit.KSYScreenStreamer;
import com.ksyun.media.streamer.capture.AudioCapture;
import com.ksyun.media.streamer.capture.AudioPlayerCapture;
import com.ksyun.media.streamer.capture.CameraCapture;
import com.ksyun.media.streamer.capture.camera.CameraTouchHelper;
import com.ksyun.media.streamer.encoder.VideoEncodeFormat;
import com.ksyun.media.streamer.filter.imgtex.ImgTexFilterBase;
import com.ksyun.media.streamer.filter.imgtex.ImgTexFilterMgt;
import com.ksyun.media.streamer.framework.AVConst;
import com.ksyun.media.streamer.kit.KSYStreamer;
import com.ksyun.media.streamer.kit.OnAudioRawDataListener;
import com.ksyun.media.streamer.kit.OnPreviewFrameListener;
import com.ksyun.media.streamer.kit.StreamerConstants;
import com.ksyun.media.streamer.logstats.StatsLogReport;
import com.netease.nim.uikit.common.fragment.TFragment;
import com.netease.nim.uikit.common.ui.dialog.EasyAlertDialogHelper;
import com.netease.nim.uikit.common.util.log.LogUtil;
import com.netease.nim.uikit.common.util.sys.ScreenUtil;
import com.netease.nim.uikit.permission.annotation.OnMPermissionDenied;
import com.netease.nim.uikit.permission.annotation.OnMPermissionGranted;
import com.netease.nim.uikit.permission.annotation.OnMPermissionNeverAskAgain;
import com.netease.nim.uikit.session.module.ModuleProxy;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.avchat.AVChatCallback;
import com.netease.nimlib.sdk.avchat.AVChatManager;
import com.netease.nimlib.sdk.avchat.AVChatStateObserver;
import com.netease.nimlib.sdk.avchat.constant.AVChatAudioEffectMode;
import com.netease.nimlib.sdk.avchat.constant.AVChatLivePIPMode;
import com.netease.nimlib.sdk.avchat.constant.AVChatMediaCodecMode;
import com.netease.nimlib.sdk.avchat.constant.AVChatResCode;
import com.netease.nimlib.sdk.avchat.constant.AVChatType;
import com.netease.nimlib.sdk.avchat.constant.AVChatUserRole;
import com.netease.nimlib.sdk.avchat.constant.AVChatVideoCaptureOrientation;
import com.netease.nimlib.sdk.avchat.constant.AVChatVideoCropRatio;
import com.netease.nimlib.sdk.avchat.constant.AVChatVideoFrameRate;
import com.netease.nimlib.sdk.avchat.constant.AVChatVideoQuality;
import com.netease.nimlib.sdk.avchat.constant.AVChatVideoScalingType;
import com.netease.nimlib.sdk.avchat.model.AVChatAudioFrame;
import com.netease.nimlib.sdk.avchat.model.AVChatCameraCapturer;
import com.netease.nimlib.sdk.avchat.model.AVChatData;
import com.netease.nimlib.sdk.avchat.model.AVChatNetworkStats;
import com.netease.nimlib.sdk.avchat.model.AVChatOptionalConfig;
import com.netease.nimlib.sdk.avchat.model.AVChatParameters;
import com.netease.nimlib.sdk.avchat.model.AVChatSessionStats;
import com.netease.nimlib.sdk.avchat.model.AVChatVideoCapturerFactory;
import com.netease.nimlib.sdk.avchat.model.AVChatVideoFrame;
import com.netease.nimlib.sdk.avchat.model.AVChatVideoRender;
import com.netease.nimlib.sdk.chatroom.ChatRoomService;
import com.netease.nimlib.sdk.chatroom.model.ChatRoomInfo;
import com.netease.nimlib.sdk.chatroom.model.ChatRoomMember;
import com.netease.nimlib.sdk.chatroom.model.ChatRoomNotificationAttachment;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.netease.nimlib.sdk.rts.RTSCallback;
import com.netease.nimlib.sdk.rts.RTSManager2;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.TreeMap;

import cn.com.nxt.txb.DemoCache;
import cn.com.nxt.txb.EnterMeetingActivity;
import cn.com.nxt.txb.HttpProtocol;
import cn.com.nxt.txb.MQTTService;
import cn.com.nxt.txb.MainActivity;
import cn.com.nxt.txb.R;
import cn.com.nxt.txb.ResponseStatus;
import cn.com.nxt.txb.SampleApplicationLike;
import cn.com.nxt.txb.TextureVideoActivity;
import cn.com.nxt.txb.adapter.ApplyAdapter;
import cn.com.nxt.txb.adapter.BusinessNumberAdapter;
import cn.com.nxt.txb.adapter.InviteAdapter;
import cn.com.nxt.txb.adapter.InviteFriendsAdapter;
import cn.com.nxt.txb.education.activity.ChatRoomActivity;
import cn.com.nxt.txb.education.adapter.ChatRoomTabPagerAdapter;
import cn.com.nxt.txb.education.fragment.tab.ChatRoomTab;
import cn.com.nxt.txb.education.helper.ChatRoomMemberCache;
import cn.com.nxt.txb.education.helper.MsgHelper;
import cn.com.nxt.txb.education.helper.VideoListener;
import cn.com.nxt.txb.education.module.ChatRoomHttpClient;
import cn.com.nxt.txb.education.module.FullScreenType;
import cn.com.nxt.txb.education.module.MeetingConstant;
import cn.com.nxt.txb.education.module.MeetingOptCommand;
import cn.com.nxt.txb.education.util.NonScrollViewPager;
import cn.com.nxt.txb.education.util.Preferences;
import cn.com.nxt.txb.fragment.HomeFragment;
import cn.com.nxt.txb.httpdelegate.BillingDelegate;
import cn.com.nxt.txb.httpdelegate.BusinessDelegate;
import cn.com.nxt.txb.httpdelegate.DialingDelegate;
import cn.com.nxt.txb.httpdelegate.LiveDelegate;
import cn.com.nxt.txb.model.ApplyMeeting;
import cn.com.nxt.txb.model.BusinessNumber;
import cn.com.nxt.txb.permission.MPermission;
import cn.com.nxt.txb.permission.util.MPermissionUtil;
import cn.com.nxt.txb.util.AppConstant;
import cn.com.nxt.txb.util.AppUtil;
import cn.com.nxt.txb.util.MyItemDecoration;
import cn.com.nxt.txb.util.OnApplyItemClickListener;
import cn.com.nxt.txb.util.OnRecyclerItemClickListener;
import cn.com.nxt.txb.widget.tab.FadeInOutPageTransformer;
import cn.com.nxt.txb.widget.tab.PagerSlidingTabStrip;
import cn.com.nxt.txb.widget.tab.reminder.ReminderId;
import cn.com.nxt.txb.widget.tab.reminder.ReminderItem;

import static com.netease.nimlib.sdk.avchat.model.AVChatParameters.*;

//import static com.ksyun.media.streamer.logstats.StatsConstant.ENCODE_TYPE;

/**
 * Created by hzxuwen on 2016/2/29.
 */
public class ChatRoomFragment extends TFragment implements AVChatStateObserver, View.OnClickListener, HttpProtocol, ServiceConnection {
    private String RTMP_URL;//"rtmp://47.93.44.39:1936/txb/test1";
    private int frameRate = 15;//采集帧率
    private int videoBitRate = 800;//视频码率(Max)
    private int audioBitRate = 48;//音频码率
    private int videoResolution = StreamerConstants.VIDEO_RESOLUTION_360P;//360p
    private int orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;//横屏
    private int encodeType = AVConst.CODEC_ID_AVC;//H264
    private int encodeMethod = StreamerConstants.ENCODE_METHOD_SOFTWARE;//软编
    private int encodeScene = VideoEncodeFormat.ENCODE_SCENE_SHOWSELF;//秀场模式
    int encodeProfile = VideoEncodeFormat.ENCODE_PROFILE_LOW_POWER;//低功耗
    boolean startAuto = false;
    boolean showDebugInfo = false;//显示调试信息
    private LiveDelegate liveDelegate;
    //private DialingDelegate dialingDelegate;
    private final byte LIVE_ADDRESS_FLAG = 0x10;
    private final byte LIVE_PLAY_FLAG = 0x11;
    private byte SEND_RECORD = (byte) 0x12;
    private final byte SIGNAL_ADDR_FLAG = 0x13;
    private final byte LIVE_START_FLAG = 0x14;
    private final static int PERMISSION_REQUEST_CAMERA_AUDIOREC = 1;
    public MQTTService.MQTTBinder mqttBinder;
    private final String TAG = "ChatRoomFragment";
    private final int LIVE_PERMISSION_REQUEST_CODE = 100;
    private Activity activity;
    private ChatRoomInfo roomInfo;
    private String roomId;
    private String roomName;
    private String shareUrl; // 分享地址
    private boolean disconnected = false; // 是否断网（断网重连用）
    private boolean isPermissionInit = false; // 是否收到其他成员权限
    private boolean isBackLayoutShow = true; // 返回布局是否显示
    private VideoListener videoListener;
    private List<String> userJoinedList = new ArrayList<>(); // 已经onUserJoined的用户
    AVChatVideoRender masterRender; // 主播画布
    //    private List<BusinessNumber> latelyNumber;
//    private InviteFriendsAdapter latelyAdapter;
    private List<BusinessNumber> contactsNumber;
    private List<BusinessNumber> selectedNumber;
    private InviteFriendsAdapter contactsAdapter;
    // private TextView latelyStatusTv;
    private TextView contactsStatusTv;
    //  private RecyclerView latelyRc;
    private RecyclerView contactsRc;
    // private AVChatCameraCapturer mVideoCapturer;

    /**
     * 聊天室TAB（下）
     */
    //private PagerSlidingTabStrip tabs;
    //private NonScrollViewPager viewPager;
    // private ChatRoomTabPagerAdapter adapter;
    // private int scrollState;

    /**
     * 直播区域（上）
     */
    private RelativeLayout videoLayout; // 直播/播放区域
    private ViewGroup backLayout;
    private ViewGroup fullScreenView; // 全屏播放显示区域
    private ViewGroup fullScreenLayout;
    private ImageView videoPermissionBtn; // 视频权限按钮
    private ImageView audioPermissionBtn; // 音频权限按钮
    private TextView interactionStartCloseBtn; // 互动开始/结束按钮
    private TextView statusText;
    private TextView roomIdText;
    private SurfaceView selfRender;
    private long uid;
    private ViewGroup masterVideoLayout; // 左上，主播显示区域
    private ViewGroup firstVideoLayout; // 第一个观众显示区域
    private ViewGroup secondVideoLayout; // 第二个观众显示区域
    private ViewGroup thirdVideoLayout; // 第三个观众显示区域
    private ViewGroup fourthVideoLayout; // 第四个观众显示区域
    private ViewGroup fifthVideoLayout; // 第五个观众显示区域
    private ViewGroup[] viewLayouts = new ViewGroup[5];
    private boolean mRecording = false;//录屏状态按钮
    //录屏直播相关
    private KSYScreenStreamer mScreenStreamer;       //kit类,封装录屏推流相关接口
    //  private KSYStreamer mStreamer;
    private int mPresetOrientation;
    //user params
    private boolean mIsLandscape;
    private int mLastRotation;
    private OrientationEventListener mOrientationEventListener;
    private boolean mAutoStart;
    private boolean mPrintDebugInfo = false;
    private boolean mHWEncoderUnsupported;
    private boolean mSWEncoderUnsupported;
    private Handler mMainHandler;
    private boolean isCreate; // true 主持人模式，false 观众模式
    private boolean isAudit;
    private String path;
    private Timer timer;
    private RTMPTask task;
    private Timer keepLiveTimer;
    private KeepLiveTask keepLiveTask;
    private BillingDelegate billingDelegate;
    /**
     * ********************************** 生命周期 **********************************
     */
    private FrameLayout mVideoFl;
    private LinearLayout mMenuLl;
    private TextView mUserStatusTv;
    private RecyclerView mUserRv;
    private ApplyAdapter mApplyAdapter;
    private LinearLayout mInviteFriendsLl;//邀请好友
    private LinearLayout mDemotionPermissionsLl;//降级权限
    private LinearLayout mStatementCancelLl;//取消发言

    private ImageView mSwapIv;
    private ImageView mMuteIv;
    private ImageView mVoiceIv;
    private ImageView mToCancelIv;//退出连麦者

    private LinearLayout mInvitePopup;
    //private TabLayout tabLayout;
    // private ViewPager pager;
    private TextView mTvCall;
    // private InviteAdapter mInviteAdapter;
    // private ArrayList<FrameLayout> frameLayouts;
    private Timer subscibeTimer;
    private SubscibeTask subscibeTask;
    private Map<String, ApplyMeeting> applyMap = new TreeMap<>();
    private List<ApplyMeeting> applyList = new ArrayList<>();
    private List<ApplyMeeting> joinList = new ArrayList<>();//连麦者

    private AlertDialog.Builder applyDialog;
    private boolean isShow = false;
    private DialingDelegate dialingDelegate;
    private AudioPlayerCapture mAudioPlayerCapture;

    //private AVChatCameraCapturer mVideoCapturer;
    //private AVChatVideoRender videoRender; // 主播画面
    protected AVChatVideoRender bypassVideoRender; // 旁路直播画面
    private AVChatCameraCapturer mVideoCapturer;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.chat_room_fragment, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        findViews();
        liveDelegate = new LiveDelegate(this);
        timer = new Timer();
        task = new RTMPTask();

        billingDelegate = new BillingDelegate(this);
        keepLiveTimer = new Timer();
        keepLiveTask = new KeepLiveTask();
        //setupPager();
        //setupTabs();
        mAudioPlayerCapture = new AudioPlayerCapture(getActivity());
        registerObservers(true);
        postDelayed(new Runnable() {
            @Override
            public void run() {
                if (!isPermissionInit) {
                    requestPermissionMembers();
                }
            }
        }, 500);
        requestLivePermission();
        getActivity().bindService(new Intent(getActivity(), MQTTService.class), this, getActivity().BIND_AUTO_CREATE);
        //IntentFilter counterActionFilter = new IntentFilter(AppConstant.MQTT_AUDIT);
        //getActivity().registerReceiver(mqttReceiver, counterActionFilter);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.activity = (ChatRoomActivity) context;
        videoListener = (VideoListener) context;
    }

    // 向所有人请求成员权限
    private void requestPermissionMembers() {
        LogUtil.d(TAG, "request permission members");
        MsgHelper.getInstance().sendCustomMsg(roomId, MeetingOptCommand.GET_STATUS);
    }

    @Override
    public void onResume() {
        super.onResume();
        // mStreamer.onResume();
        //注册广播
        IntentFilter counterActionFilter = new IntentFilter(AppConstant.MQTT_AUDIT);
        getActivity().registerReceiver(mqttReceiver, counterActionFilter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        registerObservers(false);
        if (isCreate) {
            mqttBinder.unsubscribe("/meetting/handspeak/apply/"+roomId);
            mqttBinder.unsubscribe("/meetting/handspeak/cancel/"+roomId);
        } else {
            mqttBinder.unsubscribe("/meetting/handspeak/resp/"+AppUtil.mUser.getPhone());
        }
        if (roomName != null) {
            NIMClient.getService(ChatRoomService.class).exitChatRoom(roomName);
            clearChatRoom();
            if (isCreate) {
                keepLiveTimer.cancel();
                // stopStream();
            }
        }
//        if (mMainHandler != null) {
//            mMainHandler.removeCallbacksAndMessages(null);
//            mMainHandler = null;
//        }
//        mStreamer.setOnLogEventListener(null);
//        mStreamer.release();
        getActivity().unbindService(this);
    }

    public void onBackPressed() {
        logoutChatRoom();
    }

    public void onKickOut() {
        LogUtil.d(TAG, "chat room do kick out");
        activity.finish();
    }

    private void logoutChatRoom() {
        EasyAlertDialogHelper.createOkCancelDiolag(activity, null, getString(R.string.logout_confirm),
                getString(R.string.leave), getString(R.string.cancel), true,
                new EasyAlertDialogHelper.OnDialogActionListener() {
                    @Override
                    public void doCancelAction() {

                    }

                    @Override
                    public void doOkAction() {
                        //if (roomInfo.getCreator().equals(DemoCache.getAccount())) {
                        if (isCreate) {
                            // 自己是主持人，则关闭聊天室
                            closeChatRoom();
                            String param=AppUtil.getJoinMeetingParam(AppUtil.mUser.getPhone(),AppUtil.mUser.getUsername(),roomName,roomId,2,1);
                            SampleApplicationLike.joinOrExitMeeting(billingDelegate,AppUtil.mUser.getToken(),param);
                        }else{
                            Map<String, String> map = new HashMap<>();
                            map.put("name", AppUtil.mUser.getUsername());
                            map.put("phone", AppUtil.mUser.getPhone());
                            Gson gson = new Gson();
                            if (mqttBinder == null || mqttBinder.isClientEmpty()) {
                                return;
                            }
                            mqttBinder.publish("/meetting/handspeak/cancel/" + roomId, gson.toJson(map));
                        }
                        activity.finish();
                    }
                }).show();

    }

    // 关闭聊天室
    private void closeChatRoom() {
        ChatRoomHttpClient.getInstance().closeRoom(roomName, roomInfo.getCreator(), new ChatRoomHttpClient.ChatRoomHttpCallback<String>() {
            @Override
            public void onSuccess(String s) {
                LogUtil.d(TAG, "close room success");
            }

            @Override
            public void onFailed(int code, String errorMsg) {
                LogUtil.d(TAG, "close room failed, code:" + code + ", errorMsg:" + errorMsg);
            }
        });
    }

    private void clearChatRoom() {
        LogUtil.d(TAG, "chat room do clear");
        AVChatManager.getInstance().leaveRoom(roomName, new AVChatCallback<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                LogUtil.d(TAG, "leave channel success");
            }

            @Override
            public void onFailed(int i) {
                LogUtil.d(TAG, "leave channel failed, code:" + i);
            }

            @Override
            public void onException(Throwable throwable) {

            }
        });
//        RTSManager2.getInstance().leaveSession(roomName, new RTSCallback<Void>() {
//            @Override
//            public void onSuccess(Void aVoid) {
//                LogUtil.d(TAG, "leave rts session success");
//            }
//
//            @Override
//            public void onFailed(int i) {
//                LogUtil.d(TAG, "leave rts session failed, code:" + i);
//            }
//
//            @Override
//            public void onException(Throwable throwable) {
//
//            }
//        });
        ChatRoomMemberCache.getInstance().clearRoomCache(roomId);
    }

    /**
     * ********************************** View初始化 **********************************
     */

    private void findViews() {
        // 直播区域
        videoLayout = findView(R.id.view_layout);
        backLayout = findView(R.id.back_layout);
        videoLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isBackLayoutShow) {
                    isBackLayoutShow = false;
                    backLayout.setVisibility(View.GONE);
                } else {
                    isBackLayoutShow = true;
                    backLayout.setVisibility(View.VISIBLE);
                }
            }
        });

        masterVideoLayout = findView(R.id.master_video_layout);
        firstVideoLayout = findView(R.id.first_video_layout);
        secondVideoLayout = findView(R.id.second_video_layout);
        thirdVideoLayout = findView(R.id.third_video_layout);
        fourthVideoLayout = findView(R.id.fourth_video_layout);
        fifthVideoLayout = findView(R.id.fifth_video_layout);
        mScreenStreamer = new KSYScreenStreamer(getActivity());
        mMainHandler = new Handler();
        viewLayouts[0] = firstVideoLayout;
        viewLayouts[1] = secondVideoLayout;
        viewLayouts[2] = thirdVideoLayout;
        viewLayouts[3] = fourthVideoLayout;
        viewLayouts[4] = fifthVideoLayout;
        roomIdText = findView(R.id.room_id);
        statusText = findView(R.id.online_status);
        findView(R.id.back_arrow).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        videoPermissionBtn = findView(R.id.video_permission_btn);
        audioPermissionBtn = findView(R.id.audio_permission_btn);
        interactionStartCloseBtn = findView(R.id.close_apply_btn);

        videoPermissionBtn.setOnClickListener(this);
        audioPermissionBtn.setOnClickListener(this);
        interactionStartCloseBtn.setOnClickListener(this);
        mVideoFl = findView(R.id.fl_video);
        mVideoFl.setOnClickListener(this);
        mMenuLl = findView(R.id.ll_menu);
        mInviteFriendsLl = findView(R.id.ll_invite_friends);//邀请好友
        mInviteFriendsLl.setOnClickListener(this);
        mDemotionPermissionsLl = findView(R.id.ll_demotion_permissions);//降级权限
        mDemotionPermissionsLl.setOnClickListener(this);
        mStatementCancelLl = findView(R.id.ll_statement_cancel);//取消发言
        mStatementCancelLl.setOnClickListener(this);
        mSwapIv = findView(R.id.iv_swap);
        mSwapIv.setOnClickListener(this);
        mMuteIv = findView(R.id.iv_mute);
        mMuteIv.setOnClickListener(this);
        mVoiceIv = findView(R.id.iv_voice);
        mVoiceIv.setOnClickListener(this);
        mInvitePopup = findView(R.id.ll_invite_popup);
        contactsStatusTv = findView(R.id.tv_status);
        contactsRc = findView(R.id.rc_linkman);
        mTvCall = findView(R.id.tv_call);
        mTvCall.setOnClickListener(this);
        mToCancelIv = findView(R.id.iv_statement_cancel);
        mToCancelIv.setOnClickListener(this);
        mUserStatusTv = findView(R.id.tv_user_status);
        mUserRv = findView(R.id.rv_user);
        //bypassVideoRender = findView(R.id.bypass_video_render);
        // bypassVideoRender.setZOrderMediaOverlay(true);
    }

    private void refreshUsers() {
        if (applyList.size() > 0)
            applyList.clear();
        applyList.addAll(applyMap.values());
        if (joinList.size() > 0)
            applyList.addAll(0, joinList);
        if (applyList.size() == 0) {
            mUserRv.setVisibility(View.GONE);
            mUserStatusTv.setVisibility(View.VISIBLE);
        } else if (applyList.size() > 0) {
            mUserRv.setVisibility(View.VISIBLE);
            mUserStatusTv.setVisibility(View.GONE);
        }
        //Log.e("user",applyList.size()+"--"+applyList.get(0).getPhone());
        mApplyAdapter.notifyDataSetChanged();
        if (applyList.size() == 0) {
            mUserRv.setVisibility(View.GONE);
            mUserStatusTv.setVisibility(View.VISIBLE);
        }
    }

    private OnApplyItemClickListener mOnApplyItemClickListener = new OnApplyItemClickListener() {
        @Override
        public void OnItemClick(View v, int pos, int type) {
            ApplyMeeting apply = applyList.get(pos);
            // Toast.makeText(getActivity(), "mOnApplyItemClickListener"+type, Toast.LENGTH_LONG).show();
            if (type == 0) {//0  申请状态同意
                handspeakResp(apply.getPhone(), apply.getUsername(), 1);
                apply.setStatus(1);
                applyMap.put(apply.getPhone(), apply);
            } else if (type == 1) {//1  申请状态拒绝
                handspeakResp(apply.getPhone(), apply.getUsername(), 2);
                applyMap.remove(apply.getPhone());
            } else if (type == 2) {//2  连麦状态踢出
                handspeakResp(apply.getPhone(), apply.getUsername(), 3);
                applyMap.remove(apply.getPhone());
            }
            refreshUsers();
//            currentNumber=list.get(pos);
//            if (currentNumber.getPhone().startsWith("1")) {
//                if (currentNumber.getPhone().equals(AppUtil.mUser.getPhone())) {
//                    showToast("不能呼叫自己！");
//                    return;
//                }
//                startAudioVideoCall(AVChatType.AUDIO, currentNumber.getPhone(),currentNumber.getName());
//            } else if (currentNumber.getPhone().startsWith("81")) {
//                startMeeting(currentNumber.getPhone());
//            }
        }
    };

    private StatsLogReport.OnLogEventListener mOnLogEventListener =
            new StatsLogReport.OnLogEventListener() {
                @Override
                public void onLogEvent(StringBuilder singleLogContent) {
                    Log.i(TAG, "***onLogEvent : " + singleLogContent.toString());
                }
            };

    private OnAudioRawDataListener mOnAudioRawDataListener = new OnAudioRawDataListener() {
        @Override
        public short[] OnAudioRawData(short[] data, int count, int sampleRate, int channels) {
            Log.d(TAG, "OnAudioRawData data.length=" + data.length + " count=" + count +
                    " sampleRate=" + sampleRate + " channels=" + channels);
            //audio pcm data
            return data;
        }
    };

    private OnPreviewFrameListener mOnPreviewFrameListener = new OnPreviewFrameListener() {
        @Override
        public void onPreviewFrame(byte[] data, int width, int height, boolean isRecording) {
            Log.d(TAG, "onPreviewFrame data.length=" + data.length + " " +
                    width + "x" + height + " mRecording=" + isRecording);
        }
    };

    private void setScreenScreenRecord() {
        mMainHandler = new Handler();
        mScreenStreamer.setUrl(RTMP_URL);
        // 录屏禁用麦克风
        mScreenStreamer.getAudioCapture().setAudioCaptureType(AudioCapture.AUDIO_CAPTURE_TYPE_DUMMY);
        // 使用推流SDK采集的音频数据喂给录屏SDK（mixer的index选7是因为该index在绝大多数情况下不会被用到）
        // mStreamer.getAudioMixer().getSrcPin().connect(mScreenStreamer.getAudioMixer().getSinkPin(7));
        //mAudioPlayerCapture.mSrcPin.connect(mScreenStreamer.getAudioMixer().getSinkPin(7));
        //推流帧率,若设置了无效值(<=0),该接口会抛出IllegalArgumentException异常
        int frameRate = 15;
        if (frameRate > 0) {
            mScreenStreamer.setTargetFps(frameRate);
        }
        //推流视频码率 must > 0 default value 600 * 1000 bps
        //若设置了无效值(<=0),该接口会抛出IllegalArgumentException异常
        int videoBitrate = 800;//mScreenStreamer.setAudio
        if (videoBitrate > 0) {
            mScreenStreamer.setVideoKBitrate(videoBitrate * 3 / 4, videoBitrate, videoBitrate / 4);
        }
        //推流音频码率 must >0 default value 48 * 1000 bps
        //若设置了无效值(<=0),该接口会抛出IllegalArgumentException异常
        int audioBitrate = 48;
        if (audioBitrate > 0) {
            //mScreenStreamer.setAudioKBitrate(audioBitrate);
        }

//        AudioInputBase mAudioInputBase = new AudioInputBase();
//        mScreenStreamer.connectAudioInput(mAudioInputBase);
//        //第三方音频数据ready后，输入第三方音频数据
//
//        mAudioInputBase.onAudioPCMAvailable(byteBuffer, timestamp, channels,
//                samplerate, samplefmt);

        //mScreenStreamer.setEnableAudioMix(true);
        //推流分辨率 must be <0,1,2,3>default VIDEO_RESOLUTION_360P(0)
        //若设置了无效值(<=0),该接口会抛出IllegalArgumentException异常
        int videoResolution = StreamerConstants.VIDEO_RESOLUTION_360P;
        mScreenStreamer.setTargetResolution(videoResolution);

        //编码方式  must be <2,3> default value METHOD_SOFTWARE(3)
        //若设置了无效值(ENCODE_METHOD_SOFTWARE_COMPAT)@throws IllegalArgumentException
        int encode_method = StreamerConstants.ENCODE_METHOD_SOFTWARE;
        mScreenStreamer.setEncodeMethod(encode_method);
        int encode_type = AVConst.CODEC_ID_HEVC;
        mScreenStreamer.setVideoCodecId(encode_type);

        int encodeScene = VideoEncodeFormat.ENCODE_SCENE_SHOWSELF;
        mScreenStreamer.setVideoEncodeScene(encodeScene);

        int encodeProfile = VideoEncodeFormat.ENCODE_PROFILE_LOW_POWER;
        mScreenStreamer.setVideoEncodeProfile(encodeProfile);

        //推流的横竖屏设置,默认竖屏
        int orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
        mPresetOrientation = orientation;
        if (orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR) {
            getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
        } else if (orientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            mIsLandscape = true;
            getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            mScreenStreamer.setIsLandspace(mIsLandscape);
        } else {
            mIsLandscape = false;
            getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            mScreenStreamer.setIsLandspace(mIsLandscape);
        }
        mLastRotation = getDisplayRotation();

        mOrientationEventListener = new OrientationEventListener(getActivity(),
                SensorManager.SENSOR_DELAY_NORMAL) {
            @Override
            public void onOrientationChanged(int orientation) {
                int rotation = getDisplayRotation();
                if (rotation != mLastRotation) {
                    Log.d(TAG, "Rotation changed " + mLastRotation + "->" + rotation);
                    mIsLandscape = (rotation % 180) != 0;
                    if (mPresetOrientation == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR) {
                        mScreenStreamer.setIsLandspace(mIsLandscape);
//                        if (mWaterMarkCheckBox.isChecked()) {
//                            hideWaterMark();
//                            showWaterMark();
//                        }
                    }

                    // onSwitchRotate();
                    mLastRotation = rotation;
                }
            }
        };

        mAutoStart = false;
        mPrintDebugInfo = false;
        mScreenStreamer.setEnableAutoRestart(true, 3000);
        mScreenStreamer.setMuteAudio(false);
        mScreenStreamer.setOnInfoListener(mOnInfoListener);
        mScreenStreamer.setOnErrorListener(mOnErrorListener);
        mScreenStreamer.setOnLogEventListener(mOnLogEventListener);
        startStream();
    }
//
//    private StatsLogReport.OnLogEventListener mOnLogEventListener =
//            new StatsLogReport.OnLogEventListener() {
//                @Override
//                public void onLogEvent(StringBuilder singleLogContent) {
//                    Log.i(TAG, "***onLogEvent : " + singleLogContent.toString());
//                }
//            };
//

    /**
     * 停止推流
     */
    private void stopStream() {
        //Toast.makeText(getActivity(), "停止推流",
        //       Toast.LENGTH_LONG).show();
        mScreenStreamer.stopStream();
        mAudioPlayerCapture.mSrcPin.disconnect(true);
        // mShootingText.setText(R.string.start_streaming);
        /// mShootingText.postInvalidate();
        mRecording = false;
//        if (mWaterMarkCheckBox.isChecked()) {
//            hideWaterMark();
//        }
        //  stopChronometer();
    }


    private void handleEncodeError() {
        int encodeMethod = mScreenStreamer.getVideoEncodeMethod();
        if (encodeMethod == StreamerConstants.ENCODE_METHOD_HARDWARE) {
            mHWEncoderUnsupported = true;
            if (mSWEncoderUnsupported) {
                mScreenStreamer.setEncodeMethod(
                        StreamerConstants.ENCODE_METHOD_SOFTWARE_COMPAT);
                Log.e(TAG, "Got HW encoder error, switch to SOFTWARE_COMPAT mode");
            } else {
                mScreenStreamer.setEncodeMethod(StreamerConstants.ENCODE_METHOD_SOFTWARE);
                Log.e(TAG, "Got HW encoder error, switch to SOFTWARE mode");
            }
        } else if (encodeMethod == StreamerConstants.ENCODE_METHOD_SOFTWARE) {
            mSWEncoderUnsupported = true;
            if (mHWEncoderUnsupported) {
                Log.e(TAG, "Got SW encoder error, can not streamer");
            } else {
                mScreenStreamer.setEncodeMethod(StreamerConstants.ENCODE_METHOD_HARDWARE);
                Log.e(TAG, "Got SW encoder error, switch to HARDWARE mode");
            }
        }
    }

    //
    /* 推流错误回调
     * 通过IKSYScreenStreamer.setOnErrorListener接口设置
     */
    private KSYScreenStreamer.OnErrorListener mOnErrorListener =
            new KSYScreenStreamer.OnErrorListener() {
                @Override
                public void onError(int what, int msg1, int msg2) {
                    switch (what) {
                        case StreamerConstants.KSY_STREAMER_ERROR_DNS_PARSE_FAILED:
                            Log.d(TAG, "KSY_STREAMER_ERROR_DNS_PARSE_FAILED");
                            break;
                        case StreamerConstants.KSY_STREAMER_ERROR_CONNECT_FAILED:
                            Log.d(TAG, "KSY_STREAMER_ERROR_CONNECT_FAILED");
                            break;
                        case StreamerConstants.KSY_STREAMER_ERROR_PUBLISH_FAILED:
                            Log.d(TAG, "KSY_STREAMER_ERROR_PUBLISH_FAILED");
                            break;
                        case StreamerConstants.KSY_STREAMER_ERROR_CONNECT_BREAKED:
                            Log.d(TAG, "KSY_STREAMER_ERROR_CONNECT_BREAKED");
                            break;
                        case StreamerConstants.KSY_STREAMER_ERROR_AV_ASYNC:
                            Log.d(TAG, "KSY_STREAMER_ERROR_AV_ASYNC " + msg1 + "ms");
                            break;
                        case StreamerConstants.KSY_STREAMER_VIDEO_ENCODER_ERROR_UNSUPPORTED:
                            Log.d(TAG, "KSY_STREAMER_VIDEO_ENCODER_ERROR_UNSUPPORTED");
                            break;
                        case StreamerConstants.KSY_STREAMER_VIDEO_ENCODER_ERROR_UNKNOWN:
                            Log.d(TAG, "KSY_STREAMER_VIDEO_ENCODER_ERROR_UNKNOWN");
                            break;
                        case StreamerConstants.KSY_STREAMER_AUDIO_ENCODER_ERROR_UNSUPPORTED:
                            Log.d(TAG, "KSY_STREAMER_AUDIO_ENCODER_ERROR_UNSUPPORTED");
                            break;
                        case StreamerConstants.KSY_STREAMER_AUDIO_ENCODER_ERROR_UNKNOWN:
                            Log.d(TAG, "KSY_STREAMER_AUDIO_ENCODER_ERROR_UNKNOWN");
                            break;
                        case StreamerConstants.KSY_STREAMER_AUDIO_RECORDER_ERROR_START_FAILED:
                            Log.d(TAG, "KSY_STREAMER_AUDIO_RECORDER_ERROR_START_FAILED");
                            break;
                        case StreamerConstants.KSY_STREAMER_AUDIO_RECORDER_ERROR_UNKNOWN:
                            Log.d(TAG, "KSY_STREAMER_AUDIO_RECORDER_ERROR_UNKNOWN");
                            break;
                        case KSYScreenStreamer.KSY_STREAMER_SCREEN_RECORD_UNSUPPORTED:
                            Log.d(TAG, "KSY_STREAMER_SCREEN_RECORD_UNSUPPORTED");
                            // Toast.makeText(getActivity(), "you android system is below 21, " +
                            //                 "can not use screenRecord",
                            //         Toast.LENGTH_LONG).show();
                            break;
                        case KSYScreenStreamer.KSY_STREAMER_SCREEN_RECORD_PERMISSION_DENIED:
                            Log.d(TAG, "KSY_STREAMER_SCREEN_RECORD_PERMISSION_DENIED");
                            // Toast.makeText(getActivity(), "No ScreenRecord permission, please check",
                            //         Toast.LENGTH_LONG).show();
                            break;
                        default:
                            Log.d(TAG, "what=" + what + " msg1=" + msg1 + " msg2=" + msg2);
                            break;
                    }
                    switch (what) {
                        case StreamerConstants.KSY_STREAMER_AUDIO_RECORDER_ERROR_START_FAILED:
                        case StreamerConstants.KSY_STREAMER_AUDIO_RECORDER_ERROR_UNKNOWN:
                            break;
                        case KSYScreenStreamer.KSY_STREAMER_SCREEN_RECORD_UNSUPPORTED:
                            //mChronometer.stop();
                            //mShootingText.setText(R.string.start_streaming);
                            //mShootingText.postInvalidate();
                            mRecording = false;
                            break;
                        case StreamerConstants.KSY_STREAMER_FILE_PUBLISHER_CLOSE_FAILED:
                        case StreamerConstants.KSY_STREAMER_FILE_PUBLISHER_ERROR_UNKNOWN:
                        case StreamerConstants.KSY_STREAMER_FILE_PUBLISHER_OPEN_FAILED:
                        case StreamerConstants.KSY_STREAMER_FILE_PUBLISHER_WRITE_FAILED:
                            break;
                        case StreamerConstants.KSY_STREAMER_VIDEO_ENCODER_ERROR_UNSUPPORTED:
                        case StreamerConstants.KSY_STREAMER_VIDEO_ENCODER_ERROR_UNKNOWN: {
                            handleEncodeError();
                            stopStream();
                            mMainHandler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    startStream();
                                }
                            }, 3000);
                        }
                        break;
                        default:
                            if (mScreenStreamer.getEnableAutoRestart()) {
                                // mShootingText.setText(R.string.start_streaming);
                                //  mShootingText.postInvalidate();
                                mRecording = false;
                                //  stopChronometer();
                            } else {
                                stopStream();
                                mMainHandler.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        startStream();
                                    }
                                }, 3000);
                            }
                            break;
                    }
                }
            };
//
    /**
     * 推流状态变更消息回调
     * 通过IKSYScreenStreamer.setOnInfoListener接口设置
     */
    private KSYScreenStreamer.OnInfoListener mOnInfoListener =
            new KSYScreenStreamer.OnInfoListener() {
                @Override
                public void onInfo(int what, int msg1, int msg2) {
                    switch (what) {
                        case StreamerConstants.KSY_STREAMER_OPEN_STREAM_SUCCESS:
                            Log.d(TAG, "KSY_STREAMER_OPEN_STREAM_SUCCESS");
                            // mChronometer.setBase(SystemClock.elapsedRealtime());
                            // mChronometer.start();
                            //beginInfoUploadTimer();
//                            if (mCameraPreviewWindowCheckBox.isChecked() && !mPreviewWindowShow) {
//                                startCameraPreview();
//                            }
                            break;
                        case StreamerConstants.KSY_STREAMER_FRAME_SEND_SLOW:
                            Log.d(TAG, "KSY_STREAMER_FRAME_SEND_SLOW " + msg1 + "ms");
                            // Toast.makeText(getActivity(), "Network not good!",
                            //         Toast.LENGTH_SHORT).show();
                            break;
                        case StreamerConstants.KSY_STREAMER_EST_BW_RAISE:
                            Log.d(TAG, "BW raise to " + msg1 / 1000 + "kbps");
                            break;
                        case StreamerConstants.KSY_STREAMER_EST_BW_DROP:
                            Log.d(TAG, "BW drop to " + msg1 / 1000 + "kpbs");
                            break;
                        default:
                            Log.d(TAG, "OnInfo: " + what + " msg1: " + msg1 + " msg2: " + msg2);
                            break;
                    }
                }
            };

    /**
     * 旋转摄像头预览示例代码
     */
//    private void onSwitchRotate() {
//        if (mPreviewWindowShow) {
//            int rotation = getDisplayRotation();
//            Log.i(TAG, "onSwitchRotate:" + rotation);
//            mCameraPreviewKit.setRotateDegrees(rotation);
//
//            boolean isLastLandscape = (mLastRotation % 180) != 0;
//            boolean isLandscape = (rotation % 180) != 0;
//            if (isLastLandscape != isLandscape) {
//                int width = mCameraPreview.getHeight();
//                int height = mCameraPreview.getWidth();
//                LinearLayout.LayoutParams layoutParams =
//                        new LinearLayout.LayoutParams(width, height);
//                layoutParams.gravity = Gravity.BOTTOM | Gravity.TOP
//                        | Gravity.LEFT | Gravity.RIGHT;
//                //更新CameraPreview布局
//                mFloatLayout.updateViewLayout(mCameraPreview, layoutParams);
//
//                updateViewPosition();
//            }
//        }
//    }
    private int getDisplayRotation() {
        int rotation = getActivity().getWindowManager().getDefaultDisplay().getRotation();
        switch (rotation) {
            case Surface.ROTATION_0:
                return 0;
            case Surface.ROTATION_90:
                return 90;
            case Surface.ROTATION_180:
                return 180;
            case Surface.ROTATION_270:
                return 270;
        }
        return 0;
    }

    private void requestLive() {
        if (isCreate)
            liveDelegate.liveAddress(LIVE_ADDRESS_FLAG);
        else
            liveDelegate.livePlay(roomName, LIVE_PLAY_FLAG);
    }

    // 初始化UI
    public void initLiveVideo(ChatRoomInfo roomInfo,final String roomId, String channelName, final boolean isCreate, boolean isAudit, String path, String shareUrl, ModuleProxy moduleProxy) {
        this.roomInfo = roomInfo;
        this.roomId = roomId;
        this.roomName = channelName;
        this.shareUrl = shareUrl;
        this.isCreate = isCreate;
        this.isAudit = isAudit;
        this.path = path;
        if (isCreate) {
            dialingDelegate = new DialingDelegate(this);
            //sendMeetingRecord(roomId);
            mToCancelIv.setVisibility(View.GONE);
        } else {
            mToCancelIv.setVisibility(View.VISIBLE);
        }
        if (isCreate) {
            mToCancelIv.setVisibility(View.GONE);
            mUserRv.setLayoutManager(new LinearLayoutManager(getActivity()));
            mUserRv.addItemDecoration(new MyItemDecoration());
            applyList.addAll(applyMap.values());
            mApplyAdapter = new ApplyAdapter(getActivity(), applyList);
            mApplyAdapter.setOnItemClickListener(mOnApplyItemClickListener);
            mUserRv.setAdapter(mApplyAdapter);
            if (applyList.size() == 0) {
                mUserRv.setVisibility(View.GONE);
                mUserStatusTv.setVisibility(View.VISIBLE);
            }
        } else {
            mToCancelIv.setVisibility(View.VISIBLE);
        }
        subscibeTask = new SubscibeTask();
        subscibeTimer = new Timer();
        subscibeTimer.schedule(subscibeTask, 1000, 1000);  //任务1 一秒钟后执行，每两秒执行一次。
        requestLive();
        roomIdText.setText(String.format("房间:%s", roomId));
        AVChatManager.getInstance().enableRtc();
        AVChatManager.getInstance().enableVideo();
        mVideoCapturer = AVChatVideoCapturerFactory.createCameraCapturer();
        mVideoCapturer.setAutoFocus(true);
        AVChatManager.getInstance().setupVideoCapturer(mVideoCapturer);

       // AVChatOptionalConfig avChatOptionalParam = new AVChatOptionalConfig();
      //  avChatOptionalParam.setAudioEffectNSMode(AVChatAudioEffectMode.PLATFORM_BUILTIN);

        if (isCreate) {
            liveDelegate.signalAddr(SIGNAL_ADDR_FLAG);
            //avChatOptionalParam.enableAudienceRole(false);
            try {
                JSONObject obj = new JSONObject(path);
                Log.e("path==", "--" + path);
                //avChatOptionalParam.setVideoCaptureOrientation(AVChatVideoCaptureOrientation.ORIENTATION_LANDSCAPE_RIGHT);
                //avChatOptionalParam.setVideoCropRatio(AVChatVideoCropRatio.CROP_RATIO_16_9);
//                avChatOptionalParam.setLiveUrl(obj.optString("pushUrl"));
//                avChatOptionalParam.setLivePIPMode(AVChatLivePIPMode.PIP_FLOATING_RIGHT_VERTICAL);
//                avChatOptionalParam.enableLive(true);//avChatOptionalParam.
                ChatRoomMemberCache.getInstance().savePermissionMemberbyId(roomId, DemoCache.getAccount());
                AVChatParameters avChatParameters = new AVChatParameters();
                avChatParameters.setBoolean(AVChatParameters.KEY_SESSION_LIVE_MODE, true);//打开直播开关
                avChatParameters.setInteger(AVChatParameters.KEY_SESSION_MULTI_MODE_USER_ROLE, AVChatUserRole.NORMAL);//打开多人模式
                avChatParameters.setString(AVChatParameters.KEY_SESSION_LIVE_URL, obj.optString("pushUrl"));//设置为推流的地址
                avChatParameters.setInteger(AVChatParameters.KEY_SESSION_LIVE_PIP_MODE, AVChatLivePIPMode.PIP_FLOATING_RIGHT_VERTICAL);//
                avChatParameters.setInteger(AVChatParameters.KEY_SESSION_MULTI_MODE_USER_ROLE, AVChatUserRole.NORMAL);//多人模式下用户角色设定
                avChatParameters.setBoolean(AVChatParameters.KEY_AUDIO_HIGH_QUALITY, false);//关闭高清语音开关
                avChatParameters.setString(AVChatParameters.KEY_AUDIO_EFFECT_NOISE_SUPPRESSOR, AVChatAudioEffectMode.SDK_BUILTIN);//打开降噪语音处理
                avChatParameters.setString(AVChatParameters.KEY_AUDIO_EFFECT_ACOUSTIC_ECHO_CANCELER, AVChatAudioEffectMode.SDK_BUILTIN);//打开回音消除语音处理
                avChatParameters.setString(AVChatParameters.KEY_AUDIO_EFFECT_NOISE_SUPPRESSOR, AVChatAudioEffectMode.SDK_BUILTIN);//语音前处理，降噪，用来消除语音通话的背景噪音
                avChatParameters.setBoolean(AVChatParameters.KEY_AUDIO_DTX_ENABLE, true);//语音DTX 当检测到输入语音无有效人声时，系统会减少发包大小来进行传输。
                avChatParameters.setInteger(AVChatParameters.KEY_SESSION_MULTI_MODE_USER_ROLE, AVChatUserRole.NORMAL);//多人模式下用户角色设定
                avChatParameters.setBoolean(AVChatParameters.KEY_VIDEO_DEFAULT_FRONT_CAMERA, true);//默认前置摄像头采集。
               // avChatParameters.setInteger(AVChatParameters.KEY_DEVICE_DEFAULT_ROTATION, Surface.ROTATION_270);//默认情况下设备顺时针旋转角度
                avChatParameters.setBoolean(AVChatParameters.KEY_VIDEO_ROTATE_IN_RENDING, true);//视频绘制时自动旋转。
                avChatParameters.setBoolean(AVChatParameters.KEY_AUDIO_HOWLING_SUPPRESS, true);//啸叫抑制 当设备近距离产生啸叫时，会自动检测啸叫进行抑制。
                int videoOrientation = getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT ? AVChatVideoCaptureOrientation.ORIENTATION_PORTRAIT : AVChatVideoCaptureOrientation.ORIENTATION_LANDSCAPE_RIGHT;
                avChatParameters.setInteger(AVChatParameters.KEY_VIDEO_CAPTURE_ORIENTATION, videoOrientation);
                //avChatParameters.setInteger(AVChatParameters.KEY_VIDEO_CAPTURE_ORIENTATION,  AVChatVideoCaptureOrientation.ORIENTATION_LANDSCAPE_RIGHT);//打开多人模式


                AVChatManager.getInstance().setParameters(avChatParameters);
            } catch (JSONException e) {
            }
            ChatRoomMemberCache.getInstance().savePermissionMemberbyId(roomId, DemoCache.getAccount());
        } else {
//            avChatOptionalParam.enableLive(true);//avChatOptionalParam.
//            avChatOptionalParam.enableAudienceRole(false);
            // setAudioVideoPermission();
            //avChatOptionalParam.setVideoCaptureOrientation(AVChatVideoCaptureOrientation.ORIENTATION_LANDSCAPE_LEFT);
            //avChatOptionalParam.setVideoCropRatio(AVChatVideoCropRatio.CROP_RATIO_16_9);
            //avChatOptionalParam.enableVideoRotate(true);
            //avChatOptionalParam.setDefaultFrontCamera(true);
            //avChatOptionalParam.setVideoEncoderMode(AVChatMediaCodecMode.MEDIA_CODEC_SOFTWARE);
            // AVChatManager.getInstance().enableVideo();
            // AVChatManager.getInstance().startVideoPreview();
            AVChatParameters avChatParameters = new AVChatParameters();
            avChatParameters.setBoolean(AVChatParameters.KEY_SESSION_LIVE_MODE, true);//打开直播开关
            avChatParameters.setInteger(AVChatParameters.KEY_SESSION_MULTI_MODE_USER_ROLE, AVChatUserRole.NORMAL);//打开多人模式
            avChatParameters.setBoolean(AVChatParameters.KEY_AUDIO_HIGH_QUALITY, false);//关闭高清语音开关
            avChatParameters.setString(AVChatParameters.KEY_AUDIO_EFFECT_NOISE_SUPPRESSOR, AVChatAudioEffectMode.SDK_BUILTIN);//打开降噪语音处理
            avChatParameters.setString(AVChatParameters.KEY_AUDIO_EFFECT_ACOUSTIC_ECHO_CANCELER, AVChatAudioEffectMode.SDK_BUILTIN);//打开回音消除语音处理
            avChatParameters.setString(AVChatParameters.KEY_AUDIO_EFFECT_NOISE_SUPPRESSOR, AVChatAudioEffectMode.SDK_BUILTIN);//语音前处理，降噪，用来消除语音通话的背景噪音
            avChatParameters.setBoolean(AVChatParameters.KEY_AUDIO_DTX_ENABLE, true);//语音DTX 当检测到输入语音无有效人声时，系统会减少发包大小来进行传输。
            avChatParameters.setInteger(AVChatParameters.KEY_DEVICE_DEFAULT_ROTATION, Surface.ROTATION_270);//默认情况下设备顺时针旋转角度
            avChatParameters.setBoolean(AVChatParameters.KEY_VIDEO_ROTATE_IN_RENDING, true);//视频绘制时自动旋转。
            avChatParameters.setBoolean(AVChatParameters.KEY_AUDIO_HOWLING_SUPPRESS, true);//啸叫抑制 当设备近距离产生啸叫时，会自动检测啸叫进行抑制。
            AVChatManager.getInstance().setParameters(avChatParameters);
        }
       // avChatOptionalParam.enableVideoRotate(true);
        //AVChatManager.getInstance().joinRoom(roomName, AVChatType.VIDEO, avChatOptionalParam, new AVChatCallback<AVChatData>() {

        AVChatManager.getInstance().joinRoom2(roomName, AVChatType.VIDEO, new AVChatCallback<AVChatData>() {
            @Override
            public void onSuccess(AVChatData avChatData) {
                Log.e("roomNameonSuccess", roomName + "--" + avChatData.getAccount());
                //Toast.makeText(activity, "加入房间成功" + roomName, Toast.LENGTH_SHORT).show();
                if (isCreate){
                    keepLiveTimer.schedule(keepLiveTask, 1000, 1000 * 10);  //任务1秒钟后执行，每10秒执行一次。
                    String param=AppUtil.getJoinMeetingParam(AppUtil.mUser.getPhone(),AppUtil.mUser.getUsername(),roomName,roomId,1,1);
                    SampleApplicationLike.joinOrExitMeeting(billingDelegate,AppUtil.mUser.getToken(),param);
                    Log.e("--statisticNumber_join--", "----");
                }
                // 打开话筒
//                AVChatManager.getInstance().setSpeaker(true);
//                AVChatManager.getInstance().enableRtc();
//                AVChatManager.getInstance().enableVideo();

                // 设置音量信号监听, 通过AVChatStateObserver的onReportSpeaker回调音量大小
                AVChatParameters avChatParameters = new AVChatParameters();
                avChatParameters.setBoolean(AVChatParameters.KEY_AUDIO_REPORT_SPEAKER, true);
                AVChatManager.getInstance().setParameters(avChatParameters);
            }

            @Override
            public void onFailed(int i) {
                Log.e("roomNameonFailed", roomName);
                LogUtil.d(TAG, "join channel failed, code:" + i);
                Log.e("join_room", "join_Failed" + i);
               // Toast.makeText(activity, "join channel failed, code:" + i + "--" + roomName, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onException(Throwable throwable) {

            }
        });
        updateControlUI();
        switchHandsUpLayout();
        updateVideoAudioUI();
    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        // Toast.makeText(activity, "onServiceConnected已连接", Toast.LENGTH_SHORT).show();
        mqttBinder = (MQTTService.MQTTBinder) service;
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        //Toast.makeText(activity, "onServiceDisconnected已断开", Toast.LENGTH_SHORT).show();

    }

    class KeepLiveTask extends TimerTask {

        @Override
        public void run() {
            keepLiveHandler.sendEmptyMessage(1);
        }
    }

    private Handler keepLiveHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // Toast.makeText(getActivity(), "keepLive", Toast.LENGTH_LONG).show();
            Map<String, Object> map = new HashMap<>();
            map.put("roomid", roomId);
            map.put("meetingid", roomName);
            Gson gson = new Gson();
            billingDelegate.keepLive(AppUtil.mUser.getToken(), gson.toJson(map), (byte) 0x55);
        }
    };

    class RTMPTask extends TimerTask {

        @Override
        public void run() {
            if (TextUtils.isEmpty(RTMP_URL))
                return;
            timer.cancel();
            liveHandler.sendEmptyMessage(0);
        }
    }

    private Handler liveHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // Toast.makeText(getActivity(), RTMP_URL, Toast.LENGTH_LONG).show();
            // setLive();
            setScreenScreenRecord();
        }
    };

    @Override
    public void onPause() {
        super.onPause();
        if (mOrientationEventListener != null) {
            mOrientationEventListener.disable();
        }
        getActivity().unregisterReceiver(mqttReceiver);
        //mStreamer.onPause();

        // disable audio low delay in background
//        if (mAudioLDCheckBox.isChecked()) {
//            mStreamer.setEnableAudioLowDelay(false);
//        }
    }

    private void updateControlUI() {
        if (isCreate) {
            videoPermissionBtn.setVisibility(View.VISIBLE);
            audioPermissionBtn.setVisibility(View.VISIBLE);
            interactionStartCloseBtn.setVisibility(View.GONE);
        } else if (ChatRoomMemberCache.getInstance().hasPermission(roomId, DemoCache.getAccount())) {
            videoPermissionBtn.setVisibility(View.VISIBLE);
            audioPermissionBtn.setVisibility(View.VISIBLE);
            interactionStartCloseBtn.setVisibility(View.VISIBLE);
            interactionStartCloseBtn.setText(R.string.finish);
        } else {
            videoPermissionBtn.setVisibility(View.GONE);
            audioPermissionBtn.setVisibility(View.GONE);
            interactionStartCloseBtn.setVisibility(View.VISIBLE);
            interactionStartCloseBtn.setText(R.string.interaction);
        }
    }

    public void onOnlineStatusChanged(boolean isOnline) {
        statusText.setVisibility(isOnline ? View.GONE : View.VISIBLE);
        NIMClient.getService(ChatRoomService.class).fetchRoomInfo(roomId).setCallback(new RequestCallback<ChatRoomInfo>() {
            @Override
            public void onSuccess(ChatRoomInfo chatRoomInfo) {
                roomInfo = chatRoomInfo;
                ((ChatRoomActivity) getActivity()).setRoomInfo(roomInfo);
                updateDeskShareUI();
            }

            @Override
            public void onFailed(int i) {
            }

            @Override
            public void onException(Throwable throwable) {
            }
        });
    }

    /**************************
     * 音视频权限控制
     ******************************/

    // 权限控制
    private static final String[] LIVE_PERMISSIONS = new String[]{
            Manifest.permission.CAMERA,
            Manifest.permission.RECORD_AUDIO};

    private void requestLivePermission() {
        MPermission.with(ChatRoomFragment.this).addRequestCode(LIVE_PERMISSION_REQUEST_CODE)
                .permissions(LIVE_PERMISSIONS)
                .request();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        MPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @OnMPermissionGranted(LIVE_PERMISSION_REQUEST_CODE)
    public void onLivePermissionGranted() {
        //  Toast.makeText(activity, "授权成功", Toast.LENGTH_SHORT).show();
    }

    @OnMPermissionDenied(LIVE_PERMISSION_REQUEST_CODE)
    public void onLivePermissionDenied() {
        List<String> deniedPermissions = MPermission.getDeniedPermissions(this, LIVE_PERMISSIONS);
        String tip = "您拒绝了权限" + MPermissionUtil.toString(deniedPermissions) + "，无法开启直播";
        //  Toast.makeText(activity, tip, Toast.LENGTH_SHORT).show();
    }

    @OnMPermissionNeverAskAgain(LIVE_PERMISSION_REQUEST_CODE)
    public void onLivePermissionDeniedAsNeverAskAgain() {
        List<String> deniedPermissions = MPermission.getDeniedPermissionsWithoutNeverAskAgain(this, LIVE_PERMISSIONS);
        List<String> neverAskAgainPermission = MPermission.getNeverAskAgainPermissions(this, LIVE_PERMISSIONS);
        StringBuilder sb = new StringBuilder();
        sb.append("无法开启直播，请到系统设置页面开启权限");
        sb.append(MPermissionUtil.toString(neverAskAgainPermission));
        if (deniedPermissions != null && !deniedPermissions.isEmpty()) {
            sb.append(",下次询问请授予权限");
            sb.append(MPermissionUtil.toString(deniedPermissions));
        }
        // Toast.makeText(activity, sb.toString(), Toast.LENGTH_LONG).show();
    }

    /************************** 音视频权限控制 end ******************************/

    /*************************
     * 监听
     ************************************/

    private void registerObservers(boolean register) {
        AVChatManager.getInstance().observeAVChatState(this, register);
        ChatRoomMemberCache.getInstance().registerMeetingControlObserver(meetingControlObserver, register);
        ChatRoomMemberCache.getInstance().registerRoomMemberChangedObserver(roomMemberChangedObserver, register);
        ChatRoomMemberCache.getInstance().registerRoomInfoChangedObserver(roomInfoChangedObserver, register);
    }

    ChatRoomMemberCache.MeetingControlObserver meetingControlObserver = new ChatRoomMemberCache.MeetingControlObserver() {
        @Override
        public void onAccept(String roomID) {
            if (checkRoom(roomID)) {
                return;
            }
//            chooseSpeechType();
        }

        @Override
        public void onReject(String roomID) {

        }

        @Override
        public void onPermissionResponse(String roomId, List<String> accounts) {
            if (checkRoom(roomId)) {
                return;
            }
            for (String a : accounts) {
                LogUtil.i(TAG, "on permission response, account:" + a);
                ChatRoomMemberCache.getInstance().savePermissionMemberbyId(roomId, a);
                Log.e("onVideoOn", "onPermissionResponse" + a);
                onVideoOn(a);
            }
        }

        @Override
        public void onSendMyPermission(String roomID, String toAccount) {
            if (checkRoom(roomID)) {
                return;
            }

            if (ChatRoomMemberCache.getInstance().hasPermission(roomID, DemoCache.getAccount())) {
                List<String> accounts = new ArrayList<>(1);
                accounts.add(DemoCache.getAccount());
                MsgHelper.getInstance().sendP2PCustomNotification(roomID, MeetingOptCommand.STATUS_RESPONSE.getValue(),
                        toAccount, accounts);
            }
        }

        @Override
        public void onSaveMemberPermission(String roomID, List<String> accounts) {
            if (checkRoom(roomID)) {
                return;
            }
            saveMemberPermission(accounts);
        }

        @Override
        public void onHandsUp(String roomID, String account) {
            if (checkRoom(roomID)) {
                return;
            }
            ChatRoomMemberCache.getInstance().saveMemberHandsUpDown(roomId, account, true);
            //onTabChange(true);
        }

        @Override
        public void onHandsDown(String roomID, String account) {
            if (checkRoom(roomID)) {
                return;
            }
            ChatRoomMemberCache.getInstance().saveMemberHandsUpDown(roomID, account, false);
            // onTabChange(false);
            if (ChatRoomMemberCache.getInstance().hasPermission(roomID, account)) {
                removeMemberPermission(account);
            }
        }

        @Override
        public void onStatusNotify(String roomID, List<String> accounts) {
            if (checkRoom(roomID)) {
                return;
            }
            onPermissionChange(accounts);
            updateControlUI();
        }
    };

    private boolean checkRoom(String roomID) {
        return TextUtils.isEmpty(roomId) || !roomId.equals(roomID);
    }

    ChatRoomMemberCache.RoomMemberChangedObserver roomMemberChangedObserver = new ChatRoomMemberCache.RoomMemberChangedObserver() {
        @Override
        public void onRoomMemberIn(ChatRoomMember member) {
            //  Toast.makeText(activity, "onRoomMemberIn", Toast.LENGTH_SHORT).show();
            onMasterJoin(member.getAccount());
            if (DemoCache.getAccount().equals(roomInfo.getCreator())
                    && !member.getAccount().equals(DemoCache.getAccount())) {
                // 主持人点对点通知有权限的成员列表
                // 主持人自己进来，不需要通知自己
                MsgHelper.getInstance().sendP2PCustomNotification(roomId, MeetingOptCommand.ALL_STATUS.getValue(),
                        member.getAccount(), ChatRoomMemberCache.getInstance().getPermissionMems(roomId));
            }

            if (member.getAccount().equals(roomInfo.getCreator())) {
                // 主持人重新进来,观众要取消自己的举手状态
                ChatRoomMemberCache.getInstance().saveMyHandsUpDown(roomId, false);
            }

            if (member.getAccount().equals(roomInfo.getCreator()) && DemoCache.getAccount().equals(roomInfo.getCreator())) {
                // 主持人自己重新进来，清空观众的举手状态
                ChatRoomMemberCache.getInstance().clearAllHandsUp(roomId);
                // 重新向所有成员请求权限
                requestPermissionMembers();
            }
        }

        @Override
        public void onRoomMemberExit(ChatRoomMember member) {
            // 主持人要清空离开成员的举手
            if (DemoCache.getAccount().equals(roomInfo.getCreator())) {
                ChatRoomMemberCache.getInstance().removeHandsUpMem(roomId, member.getAccount());
            }

            // 用户离开频道，如果是有权限用户，移除下画布
            if (member.getAccount().equals(roomInfo.getCreator())) {
                masterVideoLayout.removeAllViews();
            } else if (ChatRoomMemberCache.getInstance().hasPermission(roomId, member.getAccount())) {
                removeMemberPermission(member.getAccount());
            }
        }
    };

    ChatRoomMemberCache.RoomInfoChangedObserver roomInfoChangedObserver = new ChatRoomMemberCache.RoomInfoChangedObserver() {
        @Override
        public void onRoomInfoUpdate(IMMessage message) {
            ChatRoomNotificationAttachment attachment = (ChatRoomNotificationAttachment) message.getAttachment();
            if (attachment != null && attachment.getExtension() != null) {
                Map<String, Object> ext = attachment.getExtension();
                // switchFullScreen(ext);
            }
        }
    };

    private void removeMemberPermission(String account) {
        ChatRoomMemberCache.getInstance().removePermissionMem(roomId, account);
        onVideoOff(account);
        if (DemoCache.getAccount().equals(roomInfo.getCreator()) && !account.equals(DemoCache.getAccount())) {
            MsgHelper.getInstance().sendCustomMsg(roomId, MeetingOptCommand.ALL_STATUS);
        }
    }

    /*************************
     * 监听 end
     ************************************/


    private void startCameraPreviewWithPermCheck() {
        int cameraPerm = ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA);
        int audioPerm = ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.RECORD_AUDIO);
        if (cameraPerm != PackageManager.PERMISSION_GRANTED ||
                audioPerm != PackageManager.PERMISSION_GRANTED) {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                Log.e(TAG, "No CAMERA or AudioRecord permission, please check");
                // Toast.makeText(getActivity(), "No CAMERA or AudioRecord permission, please check",
                //         Toast.LENGTH_LONG).show();
            } else {
                String[] permissions = {Manifest.permission.CAMERA,
                        Manifest.permission.RECORD_AUDIO,
                        Manifest.permission.READ_EXTERNAL_STORAGE};
                ActivityCompat.requestPermissions(getActivity(), permissions,
                        PERMISSION_REQUEST_CAMERA_AUDIOREC);
            }
        } else {
            //mStreamer.startCameraPreview();
        }
    }

    private void updateVideoAudioUI() {
        videoPermissionBtn.setBackgroundResource(!AVChatManager.getInstance().isLocalVideoMuted()
                ? R.drawable.chat_room_video_on_selector : R.drawable.chat_room_video_off_selector);
        audioPermissionBtn.setBackgroundResource(!AVChatManager.getInstance().isLocalAudioMuted()
                ? R.drawable.chat_room_audio_on_selector : R.drawable.chat_room_audio_off_selector);
    }

    // 更新成员权限缓存
    private void saveMemberPermission(List<String> accounts) {
        isPermissionInit = true;
        onPermissionChange(accounts);
    }

    /*****************************
     * AVChatStateObserver
     *********************************/

    @Override
    public void onTakeSnapshotResult(String s, boolean b, String s1) {

    }

    @Override
    public void onConnectionTypeChanged(int i) {

    }

    @Override
    public void onAVRecordingCompletion(String s, String s1) {

    }

    @Override
    public void onAudioRecordingCompletion(String s) {

    }

    @Override
    public void onLowStorageSpaceWarning(long l) {

    }

    @Override
    public void onFirstVideoFrameAvailable(String s) {
        Log.e("onFirstVideoFrameAvailable", s);
    }

    @Override
    public void onVideoFpsReported(String s, int i) {

    }

    @Override
    public void onJoinedChannel(int i, String s, String s1) {
        LogUtil.d(TAG, "onJoinedChannel, res:" + i);
        if (i != AVChatResCode.JoinChannelCode.OK) {
            // Toast.makeText(activity, "joined channel:" + i, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onLeaveChannel() {
        userJoinedList.remove(DemoCache.getAccount());
    }

    @Override
    public void onUserJoined(String s) {
        userJoinedList.add(s);
        Log.e("onVideoOn", "onUserJoined--" + s);
        // Toast.makeText(activity, "1111onUserJoined" + s, Toast.LENGTH_SHORT).show();
        Log.e("onUserJoined", s);
        if (!("8" + s).equals(roomId)) {//s.equals(roomInfo.getCreator())
            onVideoOn(s);
        } else {
            onMasterJoin(s);
        }
        //Toast.makeText(activity, "2222onUserJoined" + s, Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onUserLeave(String s, int i) {
        // 用户离开频道，如果是有权限用户，移除下画布
        if (!("8" + s).equals(roomId)) {//s.equals(roomInfo.getCreator()) ChatRoomMemberCache.getInstance().hasPermission(roomId, s) &&
            Toast.makeText(activity, "onUserLeave" + s, Toast.LENGTH_SHORT).show();
            onVideoOff(s);
        } else if (("8" + s).equals(roomId)) {
            masterVideoLayout.removeAllViews();
        }
        ChatRoomMemberCache.getInstance().removePermissionMem(roomId, s);
        videoListener.onUserLeave(s);
        userJoinedList.remove(s);
    }

    @Override
    public void onProtocolIncompatible(int i) {

    }

    @Override
    public void onDisconnectServer() {

    }

    @Override
    public void onNetworkQuality(String s, int i, AVChatNetworkStats avChatNetworkStats) {

    }

    @Override
    public void onCallEstablished() {
        userJoinedList.add(DemoCache.getAccount());
        //Toast.makeText(activity, "互动直播连接成功111", Toast.LENGTH_SHORT).show();
        if (isCreate)
            onMasterJoin(DemoCache.getAccount());
        else {
            userJoinedList.add(DemoCache.getAccount());
            Log.e("onVideoOn", "onCallEstablished" + DemoCache.getAccount());
            onVideoOn(DemoCache.getAccount());
        }
        //Toast.makeText(activity, "互动直播连接成功222", Toast.LENGTH_SHORT).show();
//        if (state == AVChatTypeEnum.AUDIO.getValue()) {
//            aVChatUIManager.onCallStateChange(CallStateEnum.AUDIO);
//        } else {
//            aVChatUIManager.initSmallSurfaceView();
//            aVChatUIManager.onCallStateChange(CallStateEnum.VIDEO);
//        }
//        isCallEstablished = true;
    }

    @Override
    public void onDeviceEvent(int i, String s) {

    }

    @Override
    public void onFirstVideoFrameRendered(String s) {

    }

    @Override
    public void onVideoFrameResolutionChanged(String s, int i, int i1, int i2) {

    }

    @Override
    public boolean onVideoFrameFilter(AVChatVideoFrame avChatVideoFrame, boolean b) {
        return false;
    }

    @Override
    public boolean onAudioFrameFilter(AVChatAudioFrame avChatAudioFrame) {
        return false;
    }

    @Override
    public void onAudioDeviceChanged(int i) {

    }

    @Override
    public void onReportSpeaker(Map<String, Integer> map, int i) {
        videoListener.onReportSpeaker(map);
    }

    @Override
    public void onAudioMixingEvent(int i) {

    }

    /**************************** AVChatStateObserver end ****************************/

    /***************************
     * 画布的显示和取消
     **********************************/

    // 主持人进入频道
    private void onMasterJoin(String s) {
        //Toast.makeText(getActivity(), "主持人进入频道" + s, Toast.LENGTH_LONG).show();
        if (userJoinedList != null && userJoinedList.contains(s) && ("8" + s).equals(roomId)) {//&& s.equals(roomInfo.getCreator())) {
            Log.e("主持人进入频道","1111111");
            if (masterRender == null) {
                masterRender = new AVChatVideoRender(getActivity());
                Log.e("主持人进入频道","2222");
            }
            boolean isSetup = setupMasterRender(s, AVChatVideoScalingType.SCALE_ASPECT_BALANCED);
            if (isSetup && masterRender != null) {
                Log.e("主持人进入频道","3333");
                addIntoMasterPreviewLayout(masterRender);
                ChatRoomMemberCache.getInstance().savePermissionMemberbyId(roomId, DemoCache.getAccount());
                updateDeskShareUI();
            }
        }
    }

    private void updateDeskShareUI() {
        Map<String, Object> ext = roomInfo.getExtension();
        if (ext != null && ext.containsKey(MeetingConstant.FULL_SCREEN_TYPE)) {
            int fullScreenType = (int) ext.get(MeetingConstant.FULL_SCREEN_TYPE);
            if (fullScreenType == FullScreenType.CLOSE.getValue()) {
                // fullScreenImage.setVisibility(View.GONE);
            } else if (fullScreenType == FullScreenType.OPEN.getValue()) {
                // fullScreenImage.setVisibility(View.VISIBLE);
            }
        }
    }

    private boolean setupMasterRender(String s, int mode) {
        if (TextUtils.isEmpty(s)) {
            return false;
        }
        boolean isSetup = false;
        try {
            if (s.equals(DemoCache.getAccount())) {
                Log.e("主持人进入频道","44444");
                AVChatManager.getInstance().startVideoPreview();
                isSetup = AVChatManager.getInstance().setupLocalVideoRender(masterRender, false, mode);
            } else {
                Log.e("主持人进入频道","55555");
                isSetup = AVChatManager.getInstance().setupRemoteVideoRender(s, masterRender, false, mode);
            }
        } catch (Exception e) {
            LogUtil.e(TAG, "set up video render error:" + e.getMessage());
            e.printStackTrace();
        }
        return isSetup;
    }

    // 将主持人添加到主持人画布
    private void addIntoMasterPreviewLayout(SurfaceView surfaceView) {
        if (surfaceView.getParent() != null)
            ((ViewGroup) surfaceView.getParent()).removeView(surfaceView);
        masterVideoLayout.addView(surfaceView);
        surfaceView.setZOrderMediaOverlay(false);
    }

    // 取消全屏显示共享桌面时，显示其他画面。
    private void showView() {
        Map<Integer, String> map = ChatRoomMemberCache.getInstance().getImageMap(roomId);
        if (map == null) {
            return;
        }
        for (Map.Entry<Integer, String> entry : map.entrySet()) {
            AVChatVideoRender render = new AVChatVideoRender(getActivity());
            if (DemoCache.getAccount().equals(entry.getValue())) {
                AVChatManager.getInstance().startVideoPreview();
                AVChatManager.getInstance().setupLocalVideoRender(render, false, AVChatVideoScalingType.SCALE_ASPECT_BALANCED);
            } else {
                AVChatManager.getInstance().setupRemoteVideoRender(entry.getValue(), render, false, AVChatVideoScalingType.SCALE_ASPECT_BALANCED);
            }
            addIntoPreviewLayout(render, viewLayouts[entry.getKey()]);
        }
    }

    // 全屏显示共享桌面时，移除其他画面，否则会叠加显示
    private void removeViews() {
        for (int i = 0; i < viewLayouts.length; i++) {
            viewLayouts[i].removeAllViews();
        }
    }

    // 权限变化
    public void onPermissionChange(List<String> accounts) {
        List<String> oldAccounts = new ArrayList<>();
        if (ChatRoomMemberCache.getInstance().getPermissionMems(roomId) != null) {
            oldAccounts.addAll(ChatRoomMemberCache.getInstance().getPermissionMems(roomId));
        }
        // accounts是新的所有人权限。如果oldaccounts不在这个里面，就remove，在就add
        for (String a : oldAccounts) {
            if (a.equals(roomInfo.getCreator())) {
                continue;
            }
            if (accounts.contains(a)) {
                LogUtil.i(TAG, "on permission change, add:" + a);
                // 新增权限
                ChatRoomMemberCache.getInstance().savePermissionMemberbyId(roomId, a);
                Log.e("onVideoOn", "onPermissionChange" + a);
                onVideoOn(a);
            } else {
                LogUtil.i(TAG, "on permission change, remove:" + a);
                ChatRoomMemberCache.getInstance().removePermissionMem(roomId, a);
                onVideoOff(a);
                ChatRoomMemberCache.getInstance().setRTSOpen(false);
            }
        }

        accounts.removeAll(oldAccounts);
        for (String a : accounts) {
            ChatRoomMemberCache.getInstance().savePermissionMemberbyId(roomId, a);
            if (a.equals(roomInfo.getCreator())) {
                continue;
            }
            Log.e("onVideoOn", "onPermissionChange_____" + a);

            onVideoOn(a);
        }
    }

    // 将有权限的成员添加到画布
    public void onVideoOn(String account) {
        //Toast.makeText(activity, "旁听加入" + account, Toast.LENGTH_SHORT).show();
        Map<Integer, String> imageMap = ChatRoomMemberCache.getInstance().getImageMap(roomId);
        Log.e("onVideoOn", "111111--" + account);
        if (imageMap == null) {
            imageMap = new HashMap<>();
            Log.e("onVideoOn", "22222--" + account);
        }
        Log.e("onVideoOn", "33333--" + account);
        showView(imageMap, account);
        ChatRoomMemberCache.getInstance().saveImageMap(roomId, imageMap);
    }

    // 显示成员图像
    private void showView(Map<Integer, String> imageMap, String a) {
        Log.e("onVideoOn", "44444--" + a);
        if (userJoinedList != null && userJoinedList.contains(a) && !imageMap.containsValue(a) && imageMap.size() < 3) {
            Log.e("onVideoOn", "555555--" + a);
            for (int i = 0; i < 3; i++) {
                Log.e("onVideoOn", "666666--" + a);
                if (!imageMap.containsKey(i)) {
                    Log.e("onVideoOn", "888888--" + a);
                    AVChatVideoRender render = new AVChatVideoRender(getActivity());
                    //render.setBackgroundColor(0xffffff00);
                    boolean isSetup = false;
                    try {
                        if (DemoCache.getAccount().equals(a)) {
                            AVChatManager.getInstance().startVideoPreview();
                            isSetup = AVChatManager.getInstance().setupLocalVideoRender(render, false, AVChatVideoScalingType.SCALE_ASPECT_BALANCED);
                            Log.e("onVideoOn", isSetup + "999999--" + a);
                        } else {
                            isSetup = AVChatManager.getInstance().setupRemoteVideoRender(a, render, false, AVChatVideoScalingType.SCALE_ASPECT_BALANCED);
                            Log.e("onVideoOn", isSetup + "00000000--" + a);                                                 //AVChatVideoScalingType.SCALE_ASPECT_BALANCED
                        }
                        LogUtil.i(TAG, "setup render, creator account:" + roomInfo.getCreator() + ", render account:" + a + ", isSetup:" + isSetup);
                    } catch (Exception e) {
                        LogUtil.e(TAG, "set up video render error:" + e.getMessage());
                        e.printStackTrace();
                    }
                    if (isSetup && render != null) {
                        imageMap.put(i, a);
                        addIntoPreviewLayout(render, viewLayouts[i]);
                        if (isCreate) {
                            ApplyMeeting apply = applyMap.get(a);
                            apply.setStatus(2);
                            applyMap.remove(a);
                            joinList.add(apply);
                            refreshUsers();
                        }
                    }
                    break;
                }
            }
        } else {
            Toast.makeText(getActivity(), "超过连麦者数量，请稍候再试", Toast.LENGTH_LONG).show();
            toCancel();
        }
        Log.e("onVideoOn", "777777--" + a);
    }

    // 添加到成员显示的画布
    private void addIntoPreviewLayout(SurfaceView surfaceView, ViewGroup viewLayout) {
        Log.e("onVideoOn", "aaaaa");
        if (surfaceView == null) {
            Log.e("onVideoOn", "bbbbb");
            return;
        }
        if (surfaceView.getParent() != null) {
            ((ViewGroup) surfaceView.getParent()).removeView(surfaceView);
            Log.e("onVideoOn", "ccccc");
        }
        viewLayout.addView(surfaceView);
        Log.e("onVideoOn", "dddddddd");
        surfaceView.setZOrderMediaOverlay(true);
        Log.e("onVideoOn", "eeeeee");

    }

    // 将被取消权限的成员从画布移除, 并将角色置为初始状态
    public void onVideoOff(String account) {
        if (isCreate) {
            for (int i = 0; i < joinList.size(); i++) {
                ApplyMeeting apply = joinList.get(i);
                if (account.equals(apply.getPhone())) {
                    joinList.remove(apply);
                    refreshUsers();
                    break;
                }
            }
        }
        Log.e("onVideoOff","--------");
        Map<Integer, String> imageMap = ChatRoomMemberCache.getInstance().getImageMap(roomId);
        Log.e("onVideoOff",(imageMap==null)+"--"+imageMap.size());

        if (imageMap == null) {
            return;
        }
        removeView(imageMap, account);
        resetRole(account);
    }

    // 移除成员图像
    private void removeView(Map<Integer, String> imageMap, String account) {
        Iterator<Map.Entry<Integer, String>> it = imageMap.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<Integer, String> entry = it.next();
            if (entry.getValue().equals(account)) {
                viewLayouts[entry.getKey()].removeAllViews();
                it.remove();
                break;
            }
        }
    }

    // 恢复为观众角色
    private void resetRole(String account) {
        if (account.equals(DemoCache.getAccount())) {
            AVChatManager.getInstance().muteLocalAudio(true);
            AVChatManager.getInstance().enableAudienceRole(true);
            AVChatManager.getInstance().muteLocalAudio(false);
            AVChatManager.getInstance().muteLocalVideo(false);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.video_permission_btn:
                if (ChatRoomMemberCache.getInstance().hasPermission(roomId, DemoCache.getAccount())) {
                    setVideoState();
                }
                break;
            case R.id.audio_permission_btn:
                if (ChatRoomMemberCache.getInstance().hasPermission(roomId, DemoCache.getAccount())) {
                    setAudioState();
                }
                break;
            case R.id.close_apply_btn:
                speakRequestCancel();
                switchHandsUpLayout();
                break;
            case R.id.fl_video:
                showOrHidePopup();
                break;
            case R.id.ll_invite_friends:
                inviteFriends();
                break;
            case R.id.ll_demotion_permissions://降级

                break;
            case R.id.iv_swap://切换摄像头

                break;
            case R.id.iv_mute://静音

                break;
            case R.id.iv_voice://语音模式

                break;
            case R.id.tv_call:
                startCall();
                break;
            case R.id.iv_statement_cancel://取消发言
                Map<String, String> map = new HashMap<>();
                map.put("name", AppUtil.mUser.getUsername());
                map.put("phone", AppUtil.mUser.getPhone());
                Gson gson = new Gson();
                if (mqttBinder == null || mqttBinder.isClientEmpty()) {
                    return;
                }
                mqttBinder.publish("/meetting/handspeak/cancel/" + roomId, gson.toJson(map));
                toCancel();
                break;
        }
    }

    //取消发言
    private void toCancel() {
        Intent intent = new Intent(getActivity(), TextureVideoActivity.class);
        intent.putExtra("roomid", roomId);
        intent.putExtra("meetingid", roomInfo.getRoomId());
        intent.putExtra("path", path);// "rtmp://" + addr + ":1935/txb/" + phoneOrRoomID);
        startActivity(intent);
        getActivity().finish();
    }

    private void startCall() {
        if (selectedNumber.size() == 0) {
            Toast.makeText(getActivity(), "请先选择邀请人", Toast.LENGTH_LONG).show();
            return;
        } else {
            for (int i = 0; i < selectedNumber.size(); i++) {
                sendMqttInvite(selectedNumber.get(i));
            }
            contactsAdapter.updateDataSet((ArrayList<BusinessNumber>) contactsNumber);
            selectedNumber.clear();
            mTvCall.setBackgroundResource(R.drawable.btn_corners_gray);
            mTvCall.setText("呼叫");
        }
    }

    private void sendMqttInvite(BusinessNumber number) {
        Map<String, Object> map = new HashMap<>();
        map.put("src_name", AppUtil.mUser.getUsername());
        map.put("src_phone", AppUtil.mUser.getPhone());
        map.put("dst_name", number.getName());
        map.put("dst_phone", number.getPhone());
        map.put("roomid", AppUtil.mUser.getRommid());
        Gson gson = new Gson();
        if (mqttBinder == null || mqttBinder.isClientEmpty()) {
            return;
        }
        //mqttBinder.publish("/meetting/invlite/" + number.getPhone(), gson.toJson(map));
    }

    private void inviteFriends() {
        mMenuLl.setVisibility(View.GONE);
        mInvitePopup.setVisibility(View.VISIBLE);
        setContacts();
    }

    private void showOrHidePopup() {
//        if (mInvitePopup.getVisibility() == View.VISIBLE) {
//            mInvitePopup.setVisibility(View.GONE);
//            return;
//        }
        if (!isCreate)
            return;
        if (mMenuLl.getVisibility() == View.VISIBLE) {
            mMenuLl.setVisibility(View.GONE);
        } else {
            mMenuLl.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 推流开始停止示例
     */
//    private void onShootClick() {
//        if (mRecording) {
//            stopStream();
//        } else {
//            startStream();
//        }
//    }

    /**
     * 开始推流
     */
    private void startStream() {
        mScreenStreamer.startStream();
        mRecording = true;
    }

    private void cancelInteractionConfirm() {
        EasyAlertDialogHelper.createOkCancelDiolag(activity, getString(R.string.operation_confirm),
                getString(R.string.exit_interaction), getString(R.string.exit), getString(R.string.cancel), true,
                new EasyAlertDialogHelper.OnDialogActionListener() {
                    @Override
                    public void doCancelAction() {

                    }

                    @Override
                    public void doOkAction() {
                        MsgHelper.getInstance().sendP2PCustomNotification(roomId, MeetingOptCommand.SPEAK_REQUEST_CANCEL.getValue(),
                                roomInfo.getCreator(), null);
                        ChatRoomMemberCache.getInstance().saveMyHandsUpDown(roomId, false);
                    }
                }).show();
    }

    // 设置自己的摄像头是否开启
    private void setVideoState() {
        if (AVChatManager.getInstance().isLocalVideoMuted()) {
            videoPermissionBtn.setBackgroundResource(R.drawable.chat_room_video_on_selector);
            AVChatManager.getInstance().muteLocalVideo(false);
        } else {
            videoPermissionBtn.setBackgroundResource(R.drawable.chat_room_video_off_selector);
            AVChatManager.getInstance().muteLocalVideo(true);
        }
    }

    // 设置自己的录音是否开启
    private void setAudioState() {
        if (AVChatManager.getInstance().isLocalAudioMuted()) {
            audioPermissionBtn.setBackgroundResource(R.drawable.chat_room_audio_on_selector);
            AVChatManager.getInstance().muteLocalAudio(false);
        } else {
            audioPermissionBtn.setBackgroundResource(R.drawable.chat_room_audio_off_selector);
            AVChatManager.getInstance().muteLocalAudio(true);
        }
    }

    private void speakRequestCancel() {
        if (ChatRoomMemberCache.getInstance().hasPermission(roomId, DemoCache.getAccount())) {
            // 结束互动
            cancelInteractionConfirm();
        } else if (ChatRoomMemberCache.getInstance().isMyHandsUp(roomId)) {
            // 取消互动
            MsgHelper.getInstance().sendP2PCustomNotification(roomId, MeetingOptCommand.SPEAK_REQUEST_CANCEL.getValue(),
                    roomInfo.getCreator(), null);
            ChatRoomMemberCache.getInstance().saveMyHandsUpDown(roomId, false);
        } else {
            // 申请互动
            MsgHelper.getInstance().sendP2PCustomNotification(roomId, MeetingOptCommand.SPEAK_REQUEST.getValue(),
                    roomInfo.getCreator(), null);
            ChatRoomMemberCache.getInstance().saveMyHandsUpDown(roomId, true);
        }
    }

    // 举手布局/取消举手布局切换
    private void switchHandsUpLayout() {
        if (!ChatRoomMemberCache.getInstance().isMyHandsUp(roomId)) {
            // 没举手
            interactionStartCloseBtn.setText(R.string.interaction);
        } else if (ChatRoomMemberCache.getInstance().isMyHandsUp(roomId)
                && !ChatRoomMemberCache.getInstance().hasPermission(roomId, DemoCache.getAccount())) {
            // 举手等待主播通过
            interactionStartCloseBtn.setText(R.string.cancel);
        } else if (ChatRoomMemberCache.getInstance().hasPermission(roomId, DemoCache.getAccount())) {
            // 主播通过，进行互动
            interactionStartCloseBtn.setText(R.string.finish);
        }
    }

    @Override
    public void success(String result, byte flag) {
        if (flag == LIVE_PLAY_FLAG) {
            JSONObject obj = null;
            try {
                obj = new JSONObject(result);
            } catch (JSONException e) {
            }
            if (obj == null)
                return;
            String addr = obj.optString("addr");
            if (TextUtils.isEmpty(addr))
                return;
            RTMP_URL = "rtmp://" + addr + ":1935/txb/" + roomName;
            Log.i("--rtmp_url--", RTMP_URL);
        } else if (flag == LIVE_ADDRESS_FLAG) {
            if (TextUtils.isEmpty(result))
                return;
            RTMP_URL = "rtmp://" + result + ":1935/txb/" + roomName;
            Log.i("--rtmp_url--", RTMP_URL);
        } else if (flag == SEND_RECORD) {
            Intent intent = new Intent(AppConstant.CALL_RECORD_RELOAD);
            getActivity().sendBroadcast(intent);
        }else if(flag==SIGNAL_ADDR_FLAG){
            Log.e("--SIGNAL_ADDR--", result);
            JSONObject obj = null;
            JSONObject pathObj=null;
            try {
                obj = new JSONObject(result);
                pathObj=new JSONObject(path);
            } catch (JSONException e) {
            }
            if (obj == null)
                return;
            String addr=obj.optString("addr");
            Map<String, Object> map = new HashMap<>();
            JSONArray arr= pathObj.optJSONArray("forward_urls");
            String[] urls=new String[arr.length()];
            for (int i = 0; i < arr.length(); i++) {
                try {
                    urls[i] = arr.getString(i);
                } catch (JSONException e) {
                    urls[i] = "";
                }
            }
            map.put("pushUrl", pathObj.optString("pushUrl"));
            map.put("forward_urls", urls);
            map.put("play_back_url", pathObj.optString("play_back_url"));
            Gson gson = new Gson();
            Log.e("--LIVE_START_param--", gson.toJson(map));
            liveDelegate.liveStart(addr,gson.toJson(map),LIVE_START_FLAG);
        }else if(flag==LIVE_START_FLAG){
            Log.e("--LIVE_START--", result);
        }
    }

    @Override
    public void failure(String result, byte flag, ResponseStatus status) {

    }

    @Override
    public void finished(int flag) {

    }

    @Override
    public void cancelled(int flag) {

    }

    private BroadcastReceiver mqttReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String type = intent.getStringExtra("type");
//            if (type.equals("upgrade_apply")) {//申请升级权限
//                String name = intent.getStringExtra("name");
//                String phone = intent.getStringExtra("phone");
//                ApplyMeeting apply = new ApplyMeeting();
//                apply.setUsername(name);
//                apply.setAudit(false);
//                applyMap.put(phone, apply);
//                if (applyMap.size() == 1) {
//                    showApplyDialog(false, phone, name);
//                }
//            } else if (type.equals("upgrade_cancel")) {//申请升级权限取消
//                String phone = intent.getStringExtra("phone");
//                applyMap.remove(phone);
//            } else
            if (type.equals("hand_apply")) {//举手发言请求
                String name = intent.getStringExtra("name");
                String phone = intent.getStringExtra("phone");
                ApplyMeeting apply = new ApplyMeeting();
                apply.setUsername(name);
                apply.setPhone(phone);
                apply.setStatus(0);
                applyMap.put(phone, apply);
                refreshUsers();
//                if (applyMap.size() == 1) {
//                    showApplyDialog(true, phone, name);
//                }
            } else if (type.equals("hand_cancel")) {//取消发言
                String tic = intent.getStringExtra("tic");
                if (!tic.equals("/meetting/handspeak/cancel/" + roomId))
                    return;
                String phone = intent.getStringExtra("phone");
                // Toast.makeText(getActivity(), "取消发言"+phone, Toast.LENGTH_LONG).show();
                applyMap.remove(phone);
                refreshUsers();
            } else if (type.equals("hand_resp")) {//举手发言回复，在会议室内，只监听踢人
                String tic = intent.getStringExtra("tic");
                String phone = intent.getStringExtra("phone");
                if (!tic.equals("/meetting/handspeak/resp/" + phone))
                    return;
                int status = intent.getIntExtra("status", 0);
                if (status == 3) {
                    Toast.makeText(getActivity(), "你被主持人踢出了会议室", Toast.LENGTH_LONG).show();
                    toCancel();
                }
                // applyMap.remove(phone);
            }
        }
    };

    private void showApplyDialog(final boolean isAudit, final String phone, final String name) {
        /* @setIcon 设置对话框图标
         * @setTitle 设置对话框标题
         * @setMessage 设置对话框消息提示
         * setXXX方法返回Dialog对象，因此可以链式设置属性
         */
        applyDialog =
                new AlertDialog.Builder(getActivity());
        //applyDialog.setIcon(R.mipmap.ic_launcher);
        applyDialog.setTitle(isAudit ? "发言申请" : "升级申请");
        applyDialog.setMessage(phone + "（" + name + "）" + "的申请");
        applyDialog.setPositiveButton("同意",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        applyMap.remove(phone);
                        if (isAudit) {
                            handspeakResp(phone, name);
                        } else {
                            meetingResp(phone, name, "1");
                        }
                    }
                });
        applyDialog.setNegativeButton("拒绝",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        applyMap.remove(phone);
                        if (!isAudit) {
                            meetingResp(phone, name, "0");
                        }
                    }
                });
        // 显示
        applyDialog.show();
        isShow = true;
        applyDialog.setOnDismissListener(dismissListener);
    }

    private void handspeakResp(String phone, String name, int status) {
        Map<String, Object> map = new HashMap<>();
        map.put("name", name);
        map.put("phone", phone);
        map.put("status", new Integer(status));
        Gson gson = new Gson();
        if (mqttBinder == null || mqttBinder.isClientEmpty()) {
            return;
        }
        mqttBinder.publish("/meetting/handspeak/resp/" + phone, gson.toJson(map));
    }

    private void handspeakResp(String phone, String name) {
        Map<String, Object> map = new HashMap<>();
        map.put("name", name);
        map.put("phone", phone);
        map.put("wait_num", new Integer(0));
        Gson gson = new Gson();
        if (mqttBinder == null || mqttBinder.isClientEmpty()) {
            return;
        }
        mqttBinder.publish("/meetting/handspeak/resp/" + phone, gson.toJson(map));
    }

    private void meetingResp(String phone, String name, String status) {
        Map<String, Object> map = new HashMap<>();
        map.put("name", name);
        map.put("phone", phone);
        map.put("status", new Integer(status));
        Gson gson = new Gson();
        if (mqttBinder == null || mqttBinder.isClientEmpty()) {
            return;
        }
        mqttBinder.publish("/meetting/in/resp/" + AppUtil.mUser.getRommid(), gson.toJson(map));
    }

    private DialogInterface.OnDismissListener dismissListener = new DialogInterface.OnDismissListener() {
        @Override
        public void onDismiss(DialogInterface dialog) {
            isShow = false;
            if (applyMap.size() > 0) {
                Iterator<String> iter = applyMap.keySet().iterator();
                if (iter.hasNext()) {
                    String phone = iter.next();
                    showApplyDialog(applyMap.get(phone).isAudit(), phone, applyMap.get(phone).getUsername());
                }
            }
        }
    };

    private void setContacts() {
        if (contactsNumber != null) {
            if (contactsNumber.size() > 0) {
                contactsStatusTv.setVisibility(View.GONE);
                contactsRc.setVisibility(View.VISIBLE);
            } else {
                contactsStatusTv.setVisibility(View.VISIBLE);
                contactsRc.setVisibility(View.GONE);
                contactsStatusTv.setText("通讯录读取失败");
            }
            return;
        }
        contactsStatusTv.setVisibility(View.VISIBLE);
        contactsRc.setVisibility(View.GONE);
        Cursor cursor = null;
        try {
            cursor = getActivity().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
            if (cursor != null) {
                contactsNumber = new ArrayList<>();
                while (cursor.moveToNext()) {
                    BusinessNumber number = new BusinessNumber();
                    String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                    number.setName(displayName);
                    String phone = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    number.setPhone(phone);
                    contactsNumber.add(number);
                    Log.i("--namephone--", displayName + "--" + phone);
                }
                // Toast.makeText(getActivity(), "通讯录长度：" + contactsNumber.size(), Toast.LENGTH_LONG).show();
                contactsAdapter = new InviteFriendsAdapter(getActivity(), contactsNumber);
                contactsAdapter.setOnItemClickListener(mOnItemClickListener);
                contactsRc.setLayoutManager(new LinearLayoutManager(getActivity()));
                contactsRc.addItemDecoration(new MyItemDecoration());
                contactsRc.setAdapter(contactsAdapter);
                contactsStatusTv.setVisibility(View.GONE);
                contactsRc.setVisibility(View.VISIBLE);
            } else {
                contactsStatusTv.setText("通讯录读取失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null)
                cursor.close();
        }
    }

    private OnRecyclerItemClickListener mOnItemClickListener = new OnRecyclerItemClickListener() {
        @Override
        public void OnItemClick(View v, int pos) {
            selectedNumber = contactsAdapter.getSelectedItem();
            if (selectedNumber.size() == 0) {
                mTvCall.setBackgroundResource(R.drawable.btn_corners_gray);
                mTvCall.setText("呼叫");
            } else {
                mTvCall.setBackgroundResource(R.drawable.bg_corners_btn);
                mTvCall.setText("呼叫" + selectedNumber.size());
            }
        }
    };

    private void setAudioVideoPermission() {
        if (!ChatRoomMemberCache.getInstance().hasPermission(roomId, AppUtil.mUser.getPhone())) {
            List<String> accounts = ChatRoomMemberCache.getInstance().getPermissionMems(roomId);
            if (accounts != null && accounts.size() > 3) {
                Toast.makeText(getActivity(), "互动人数已满！", Toast.LENGTH_SHORT).show();
                return;
            }
            // 取消发言显示
            ChatRoomMemberCache.getInstance().saveMemberHandsUpDown(roomId, AppUtil.mUser.getPhone(), false);
            // 同意连麦请求
            MsgHelper.getInstance().sendP2PCustomNotification(roomId, MeetingOptCommand.SPEAK_ACCEPT.getValue(),
                    AppUtil.mUser.getPhone(), null);
            // 更新本地权限缓存, 添加新的成员
            ChatRoomMemberCache.getInstance().savePermissionMemberbyId(roomId, AppUtil.mUser.getPhone());
            Log.e("onVideoOn", "setAudioVideoPermission");
            // 将成员图像显示到画图上
            videoListener.onVideoOn(AppUtil.mUser.getPhone());
        } else {
            // 挂断连麦请求
            MsgHelper.getInstance().sendP2PCustomNotification(roomId, MeetingOptCommand.SPEAK_REJECT.getValue(),
                    AppUtil.mUser.getPhone(), null);
            // 更新本地权限缓存，移除成员
            ChatRoomMemberCache.getInstance().removePermissionMem(roomId, AppUtil.mUser.getPhone());
            // 将成员图像从画布移除
            videoListener.onVideoOff(AppUtil.mUser.getPhone());
        }
    }

    class SubscibeTask extends TimerTask {

        @Override
        public void run() {
            if (mqttBinder == null || mqttBinder.isClientEmpty()) {
                return;
            }
            subscibeTimer.cancel();
            if (isCreate) {
                mqttBinder.subscribe("/meetting/handspeak/apply/"+roomId);
                mqttBinder.subscribe("/meetting/handspeak/cancel/"+roomId);
            } else {
                mqttBinder.subscribe("/meetting/handspeak/resp/"+AppUtil.mUser.getPhone());
            }
            // mqttBinder.subscribe("/meetting/in/apply/#");
            // mqttBinder.subscribe("/meetting/in/cancel/#");
            //Log.i("111---","123321");
        }
    }

    private void sendMeetingRecord(String account) {
        Map<String, Object> map = new HashMap<>();
        map.put("name", AppUtil.mUser.getUsername());
        map.put("phone", account);
        map.put("type", new Integer(2));
        map.put("direct", new Integer(1));
        map.put("status", new Integer(0));
        Gson gson = new Gson();
        dialingDelegate.callRecord(gson.toJson(map), AppUtil.mUser.getToken(), SEND_RECORD);
    }

    @Override
    public void onLiveEvent(int i) {

    }

    @Override
    public void onSessionStats(AVChatSessionStats avChatSessionStats) {

    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if(!isCreate)
            return;
        AVChatParameters parameters = new AVChatParameters();
        int videoOrientation = getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT ? AVChatVideoCaptureOrientation.ORIENTATION_PORTRAIT : AVChatVideoCaptureOrientation.ORIENTATION_LANDSCAPE_RIGHT;
        parameters.setInteger(AVChatParameters.KEY_VIDEO_CAPTURE_ORIENTATION, videoOrientation);
        AVChatManager.getInstance().setParameters(parameters);
    }
}
